<script setup lang="ts">
import {reactive, ref, watch} from "vue";
import {CircleCloseFilled} from "@element-plus/icons-vue";
import {getFileFormat} from "@/utils/file.ts";
import {download} from "@/api/file/fileList.ts";
import {downloadBlob} from "@/utils/downloadBlob.ts";
import {createHashFile} from "@/utils/HashFixedSalt.ts";
import {ElMessage} from "element-plus";
import ChunkAni from "@/components/particle/chunkAni.vue";

// import { renderAsync } from 'docx-preview'



const props = defineProps ({
  downloadDialogVisible:{
    type:Boolean,
    required:true
  },
  fileTitle:{
    type:String,
    required:true
  },
  fileDate:{
    type:Object,
    required:true
  }
})
let fileIcon = ''
const dialogVisible = ref(props?.downloadDialogVisible)

watch(()=>props.downloadDialogVisible,(newValue)=>{
  dialogVisible.value = newValue
})
watch(()=>props.fileTitle,()=>{
   fileIcon = getFileFormat(props.fileTitle)
})
const emits = defineEmits(['close']);
const handleClose = ()=>{
  emits('close');
}

const downLoad = reactive({
  loading:false
})

// let iframeUrl = ''
let container = ref();

const downloadFile = ()=>{
  downLoad.loading = true
  const fileId = props.fileDate.fileId
   download(fileId).then(res=>{
    const headerHash = res.headers.hash
    const reader = new FileReader();
    reader.onload = (e:any) =>{
      const bytes = e.target.result
      const hash = createHashFile(bytes).hashedFile.toString()
      downLoad.loading = false
      if(hash===headerHash){
        downloadBlob(res.data, props.fileTitle);
      }else{
        ElMessage.error('当前文件未上传成功，请重新上传')
      }
    }
    reader.readAsArrayBuffer(res.data)

  })
}

</script>

<template>

  <el-dialog
      v-model="dialogVisible"
      fullscreen
      :show-close="false"
      :close-on-press-escape="false"
  >
    <div ref="container" class="docx"></div>
    <template #header="{titleId, titleClass }">
      <div class="my-header">
        <h4 :id="titleId" :class="titleClass">{{props.fileTitle}}</h4>
        <el-button type="danger" class="my-button" @click="handleClose">
          <el-icon class="el-icon--left"><CircleCloseFilled /></el-icon>
          关闭
        </el-button>
      </div>
    </template>
    <div class="file-context">
      <el-icon :class="fileIcon" :size="80"/>
      <p>{{props.fileTitle}}</p>
      <el-button class="download-button" @click="downloadFile">下载</el-button>
    </div>
      <chunk-ani v-show="downLoad.loading"/>
  </el-dialog>

</template>

<style scoped lang="scss">
.my-header{
  flex-direction: row;
  font-size: 16px;
  font-weight: bold;

  .my-button{
    position: absolute;
    top: 6px;
    left: 0;
    margin: 15px;
  }
}
.file-context{
  .download-button{
    height: 36px;
    min-width: 100px;
    color: #ffffff;
    background: linear-gradient(to right, #79bbff, #ff7a7a);
  }

  .download-button:hover{
    background: linear-gradient(to right, #79bbff, #ef1313);
  }
}
</style>
